<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable placeholder="参数名" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="580px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <!--          <el-form-item label="ID" prop="paraId">
            <el-input v-model="form.paraId" style="width: 370px;" />
          </el-form-item>-->
          <el-form-item label="参数编码" prop="code">
            <el-input v-model="form.code" />
          </el-form-item>
          <el-form-item label="参数名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="参数类型" prop="type">
            <el-radio v-for="item in dict.parameter_type" :key="item.id" v-model="form.type" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
          <el-form-item v-if="form.type=== '1'" label="参数值" prop="value">
            <el-input v-model="form.value" />
          </el-form-item>
          <!--          -->
          <!--          <el-form-item v-if="form.type === 1" :label="$t('systemParameter.parameterValue')+$t('common.colon')" prop="parameterValue">
            <el-input v-model="formData.parameterValue" class="input-text-max-width" :maxlength="1000" type="textarea" :rows="2" :show-word-limit="true" resize="none" placeholder="请输入参数值" clearable />
          </el-form-item>-->
          <el-form-item v-if="form.type === '2'" label="参数值" prop="imageValue">
            <el-upload
              :limit="limit"
              :headers="headers"
              style="margin-top: 5px;display: inline-block;"
              :accept="acceptFile('img')"
              action="#"
              :auto-upload="true"
              :on-remove="handleRemove"
              list-type="picture-card"
              :on-error="uploadError"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :http-request="httpRequest"
              :file-list="fileList"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">上传文件只能是 png/jpg/jpeg/gif 格式！大小不能超过{{ formMaxSize }}M！</div>
            </el-upload>
          </el-form-item>
          <!--          -->
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 320px)" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="paraId" label="ID" />
        <el-table-column prop="code" label="参数编码" />
        <el-table-column prop="name" label="参数名" />
        <el-table-column prop="type" label="参数类型">
          <template slot-scope="scope">
            {{ dict.label.parameter_type[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="value" label="参数值" />
        <el-table-column prop="description" label="描述" />
        <el-table-column v-if="checkPer(['admin','parameters:edit','parameters:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>

import crudParameters from '@/api/parameters/index'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { uploadFile } from '../../../api/parameters'
const defaultForm = { paraId: null, code: null, name: null, type: null, value: null, description: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'Parameters',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['parameter_type'],
  cruds() {
    return CRUD({ title: '参数设置', url: 'api/parameters', idField: 'paraId', sort: 'paraId,desc', crudMethod: { ...crudParameters }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'parameters:add'],
        edit: ['admin', 'parameters:edit'],
        del: ['admin', 'parameters:del'],
        download: ['admin', 'parameters:download']
      },
      rules: {
        paraId: [
          { required: true, message: 'ID不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '参数编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '参数名不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '参数类型不能为空', trigger: 'blur' }
        ],
        value: [
          { min: 0, max: 5000, message: '长度不能超过5000个字符', trigger: 'blur' }
        ],
        /*   imageValue: [
          { min: 0, max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        ],*/
        description: [
          { min: 0, max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '参数名' }
      ],
      show: false,
      headers: {
        'Authorization': getToken()
      },
      imagelist: [],
      limit: 1,
      /* 上传文件大小*/
      formMaxSize: 10,
      /* 文本值*/
      imageValue: '',
      fileList: []
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  methods: {
    /* 新增时清空*/
    [CRUD.HOOK.beforeToAdd](crud, form) {
      this.fileList = []
      this.form.value = ''
      this.imageValue = ''
    },
    /* 初始化编辑*/
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.fileList = []
      if (crud.form.type === '1') {
        this.form.value = crud.form.value
        this.imageValue = ''
      }
      if (crud.form.type === '2') {
        this.fileList = crud.form.value ? [{ name: crud.form.value, url: this.baseApi + crud.form.value }] : []
        this.filelist = []
        this.form.value = ''
      }
    },
    /* 提交前做的操作*/
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.form.type === '1') {
        crud.form.value = this.form.value
      }
      if (this.form.type === '2') {
        crud.form.value = this.imageValue
      }
    },
    /* 实现图片上传功能*/
    httpRequest(item) {
      /* 定义FormData对象 存储文件*/
      const mf = new FormData()
      /* 将图片文件放入mf*/
      mf.append('file', item.file)
      uploadFile(mf).then((data) => {
        /* 该路径linux下无法使用，作废*/
        /* this.imageValue = data.path
        const value = this.imageValue.split('\\').filter(Boolean)
        this.imageValue = '/' + value.slice(2).join('/')
        this.fileList = [{ name: this.imageValue, url: this.baseApi + this.imageValue }]*/
        /* 路径获取*/
        this.imageValue = '/file/图片/' + data.realName
        this.fileList = [{ name: this.imageValue, url: this.baseApi + this.imageValue }]
        this.$message.success('图片上传成功')
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    /* 图片上传超过数量限制*/
    handleExceed(file, fileList) {
      this.$message.error('上传图片不能超过' + this.limit + '张!')
    },
    /* 移除上传列表中文件*/
    handleRemove(file, filelist) {
      file = []
      this.imageValue = ''
      this.filelist = []
      this.fileList.splice(0, this.fileList.length)
    },
    /* 上传图片*/
    uploadError() {
      this.$message.error('上传图片失败')
    },
    /* 上传图片之后的方法*/
    fileUploadSuccess(response, file, filelist) {
      /* this.form.value = URL.createObjectURL(file.raw).substring(URL.createObjectURL(file.raw).lastIndexOf('/') + 1)*/
    },
    /* 文件格式*/
    acceptFile(e) {
      const allowHook = {
        video: '.mp4, .ogv, .ogg, .webm',
        audio: '.wav, .mp3, .ogg, .acc, .webm, .amr',
        file: 'doc,.docx,.xlsx,.xls,.pdf',
        excel: 'xlsx,.xls',
        img: '.jpg, .jpeg, .png, .gif'
      }
      if (e) {
        return allowHook[e]
      }
      let srt = null
      for (const k in allowHook) {
        srt += allowHook[k]
      }
      return srt
    },
    /* 开始上传前验证*/
    beforeUpload(file) {
      /* 验证文件类型*/
      if (file.name) {
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'png' || testmsg === 'jpg' || testmsg === 'jpeg' || testmsg === 'gif'
        if (!extension) {
          this.$message.error('上传格式错误')
        }
        return extension
      }
      /* 验证文件大小*/
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: '文件大小不能超过' + this.formMaxSize + 'M！',
          type: 'warning'
        })
        return false
      }
    },
    /* 钩子：在获取表格数据之前执行，false 则代表不获取数据*/
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>
/deep/.el-upload-list__item.is-ready,.el-upload-list__item.is-uploading{
  /*display: none !important;*/
  transition: none !important;
}
::v-deep .el-list-leave-to{
  transition: none !important;
}
::v-deep .el-list-enter-to {
  transition: none !important;
}

</style>
